package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.PanelContentItemDto;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class HomeServiceImpl implements IHomeService {

    @Autowired
    private PanelMapper panelMapper;

    @Autowired
    private PanelContentMapper contentMapper;

    @Autowired
    private ContentConverter converter;

    @Override
    public Set<PanelDto> homepage() {
        Set<PanelDto> set = new HashSet<>();
        Example example = new Example(Panel.class);
        example.createCriteria().andEqualTo("position", 0);
        List<Panel> panels = panelMapper.selectByExample(example);
        for (Panel panel : panels) {
            List<PanelContentItem> contentItems = contentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
            List<PanelContentItemDto> itemDtoList = converter.panelContentItem2Dto(
                    contentItems.subList(0, Math.min(contentItems.size(), panel.getLimitNum())));
            PanelDto panelDto = converter.panel2Dto(panel);
            panelDto.setPanelContentItems(itemDtoList);
            set.add(panelDto);
        }
        return set;
    }
}
